package com.nananren.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nananren.anno.OperateLogLog;
import com.nananren.common.MyThreadLocal;
import com.nananren.common.Result;
import com.nananren.domain.Book;
import com.nananren.domain.Borrow;
import com.nananren.domain.Category;
import com.nananren.dto.BookDto;
import com.nananren.exception.CustomerException;
import com.nananren.service.BookService;
import com.nananren.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/book")
@Slf4j
//@CrossOrigin(origins = "http://localhost:8081")
public class BookController {

    @Autowired
    private BookService bookService;

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public Result save(@RequestBody BookDto bookDto) {
        log.info("新增图书，信息为：{}", bookDto);
        // 1.判断该图书所属分类是否存在
        String categoryName = bookDto.getCategoryName();
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.eq(Category::getType, categoryName);
        Category category = categoryService.getOne(categoryLambdaQueryWrapper);
        if (category == null) {
            return Result.error("当前分类不存在!!");
        }
        // 2.如果存在，将分类名称对应的分类id存入bookDto
        Long categoryId = category.getId();
        bookDto.setCategoryId(categoryId);

        // 2.判断数据库中isDeleted字段为0的数据中是否有和传递的name相同的数据
        String name = bookDto.getName();
        LambdaQueryWrapper<Book> bookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        bookLambdaQueryWrapper.eq(Book::getName, name);
        bookLambdaQueryWrapper.eq(Book::getIsDeleted, 0);
        Book bookInDB = bookService.getOne(bookLambdaQueryWrapper);
        // (1)如果有则将isDeleted修改为1即可，并修改其他数据
        if (bookInDB != null) {
            // 对象拷贝
            // 需要忽略id属性，因为前端传递过来的id为null，会导致更新失败
            BeanUtils.copyProperties(bookDto, bookInDB, "id");
            // 手动添加createTime、createUser、isDeleted
            bookInDB.setCreateTime(LocalDateTime.now());
            bookInDB.setCreateUser(MyThreadLocal.getLocal());
            bookInDB.setIsDeleted(1);
            bookService.updateById(bookInDB);
            return Result.success("新增成功");
        }
        // (2)如果没有则正常添加
        bookService.save(bookDto);
        return Result.success("新增成功");




    }

    // 根据id删除图书
    @DeleteMapping("/{id}")
    @CrossOrigin
    public Result deleteById(@PathVariable Long id) {
        log.info("根据ID删除图书，id为：{}", id);
        // 根据id和isDeleted查询该图书是否存在
        LambdaQueryWrapper<Book> bookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        bookLambdaQueryWrapper.eq(Book::getId, id);
        bookLambdaQueryWrapper.eq(Book::getIsDeleted, 1);
        Book book = bookService.getOne(bookLambdaQueryWrapper);
        // 说明数据库中存在该图书
        if(book != null) {
            book.setIsDeleted(0);
            bookService.updateById(book);
            return Result.success("删除成功");
        }

        // 说明数据库中不存在该图书
        return Result.error("当前图书不存在!!");
    }

    // 批量删除图书
    @DeleteMapping("/isDeleted/0")
    public Result deleteByIds(@RequestParam("ids") List<Long> ids) {
        log.info("批量删除图书，ids为：{}", ids);
        // 条件构造器
        LambdaQueryWrapper<Book> bookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        bookLambdaQueryWrapper.eq(Book::getIsDeleted, 1);
        bookLambdaQueryWrapper.in(ids.size() != 0,  Book::getId, ids);
        List<Book> list = bookService.list(bookLambdaQueryWrapper);
        // 说明id有不存在的情况
        if (list.size() != ids.size()) {
            return Result.error("当前图书不存在!");
        }
        // 把每一个图书的is_deleted字段设置为0
        list = list.stream().map(item -> {
            item.setIsDeleted(0);
            return item;
        }).collect(Collectors.toList());

        // 根据list批量删除
        bookService.updateBatchById(list);

        return Result.success("删除成功");
    }

    // 修改图书
    @PutMapping
    public Result updateById(@RequestBody BookDto bookDto) {
        log.info("修改图书信息，图书信息为，{}", bookDto.toString());
        // 1.判断该图书所属分类是否存在
        String categoryName = bookDto.getCategoryName();
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.eq(Category::getType, categoryName);
        Category category = categoryService.getOne(categoryLambdaQueryWrapper);
        if (category == null) {
            return Result.error("当前分类不存在!!");
        }
        // 将分类id赋值给bookDto里面的categoryId
        bookDto.setCategoryId(category.getId());

        // 正常修改
        bookService.updateById(bookDto);
        return Result.success("修改成功!");
    }

    // 根据id查询图书
    @GetMapping("/{id}")
    public Result getById(@PathVariable Long id) {
        //条件构造器
        LambdaQueryWrapper<Book> bookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        bookLambdaQueryWrapper.eq(Book::getIsDeleted, 1);
        bookLambdaQueryWrapper.eq(Book::getId, id);
        Book book = bookService.getOne(bookLambdaQueryWrapper);
        // 判断图书是否存在
        if (book == null) {
            return Result.error("当前数据不存在");
        }
        BookDto bookDto = new BookDto();
        // 对象拷贝
        BeanUtils.copyProperties(book, bookDto);
        Category category = categoryService.getById(book.getCategoryId());
        if (category == null) {
            return Result.error("数据有误");
        }
        bookDto.setCategoryName(category.getType());
        return Result.success(bookDto);
    }

    // 查询全部图书信息
    @GetMapping("/list")
    @CrossOrigin
    public Result list() {
        LambdaQueryWrapper<Book> bookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        bookLambdaQueryWrapper.eq(Book::getIsDeleted, 1);
        List<Book> list = bookService.list(bookLambdaQueryWrapper);
        return list.size() != 0 ? Result.success(list) : Result.error("暂无数据");
    }

    // 图书信息分页条件查询
//    @GetMapping("/page")
//    public Result page(int page, int pageSize, String name) {
//        log.info("分页查询条件：{},{},{}", page, pageSize, name);
//        //分页构造器
//        Page<Book> bookPage = new Page<>(page, pageSize);
//        Page<BookDto> bookDtoPage = new Page<>();
//        // 条件构造器
//        LambdaQueryWrapper<Book> bookLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        // 没有被删除
//        bookLambdaQueryWrapper.eq(Book::getIsDeleted, 1);
//        // 根据name模糊匹配
//        bookLambdaQueryWrapper.like(name != null, Book::getName, name);
//        // 根据更新时间倒序排序
//        bookLambdaQueryWrapper.orderByDesc(Book::getUpdateTime);
//        // 分页查询
//        bookService.page(bookPage, bookLambdaQueryWrapper);
//        // 对象拷贝
//        BeanUtils.copyProperties(bookPage, bookDtoPage, "records");
//        List<Book> records = bookPage.getRecords();
//        List<BookDto> BookDtoRecords = records.stream().map(item -> {
//            BookDto bookDto = new BookDto();
//            // 对象拷贝
//            BeanUtils.copyProperties(item, bookDto);
//            // 处理categoryName
//            // 根据categoryId获取categoryName
//            Category category = categoryService.getById(item.getCategoryId());
//            if (category != null) {
//                bookDto.setCategoryName(category.getType());
//            }
//            return bookDto;
//        }).collect(Collectors.toList());
//
//        // 将records赋值给bookDtoPage
//        bookDtoPage.setRecords(BookDtoRecords);
//
//        return bookDtoPage.getTotal() != 0 ? Result.success(bookDtoPage) : Result.error("暂无数据");
//    }

    // 图书信息分页查询
    @GetMapping("/page")
    public Result page(int page, int pageSize, String name, String categoryName,
                       @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime begin,
                       @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime end) {
        log.info("分页查询条件：{},{},{},{},{},{}", page, pageSize, name, categoryName, begin, end);
        //分页构造器
        Page<Book> bookPage = new Page<>(page, pageSize);
        Page<BookDto> bookDtoPage = new Page<>();
        // 条件构造器
        LambdaQueryWrapper<Book> bookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 没有被删除
        bookLambdaQueryWrapper.eq(Book::getIsDeleted, 1);
        // 根据name模糊匹配
        bookLambdaQueryWrapper.like(name != null, Book::getName, name);
        // 日期条件
        // begin等于null，end不等于null，查询borrow_time小于等于end的所有数据
        bookLambdaQueryWrapper.le(begin == null && end != null, Book::getCreateTime, end);
        // begin不等于null，end等于null，查询borrow_time大于等于begin的所有数据
        bookLambdaQueryWrapper.ge(begin != null && end == null, Book::getCreateTime, begin);
        // begin和end都不等于null，查询borrow_time大于等于begin并小于等于end的所有数据
        bookLambdaQueryWrapper.between(begin != null && end != null, Book::getCreateTime, begin, end);
        // 分类名称
        // 因为前端传递的分类名称是下拉框选择的精确名称，所以后端精确查询就可以了，先把这个分类的id查出来，再通过Book.getCategoryId在这个ids里面
        // 就可以了
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.eq(categoryName != null, Category::getType, categoryName);
        categoryLambdaQueryWrapper.eq(categoryName != null, Category::getIsDeleted, 1);
        List<Category> list = categoryService.list(categoryLambdaQueryWrapper);
        if (list.size() == 0) {
            return Result.error("当前分类不存在");
        }
        // stream流得到每一个id
        List<Long> ids = list.stream().map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        bookLambdaQueryWrapper.in(Book::getCategoryId, ids);
        // 根据更新时间倒序排序
        bookLambdaQueryWrapper.orderByDesc(Book::getUpdateTime);
        // 分页查询
        bookService.page(bookPage, bookLambdaQueryWrapper);
        // 对象拷贝
        BeanUtils.copyProperties(bookPage, bookDtoPage, "records");
        List<Book> records = bookPage.getRecords();
        List<BookDto> BookDtoRecords = records.stream().map(item -> {
            BookDto bookDto = new BookDto();
            // 对象拷贝
            BeanUtils.copyProperties(item, bookDto);
            // 处理categoryName
            // 根据categoryId获取categoryName
            Category category = categoryService.getById(item.getCategoryId());
            if (category != null) {
                bookDto.setCategoryName(category.getType());
            }
            return bookDto;
        }).collect(Collectors.toList());

        // 将records赋值给bookDtoPage
        bookDtoPage.setRecords(BookDtoRecords);

        return bookDtoPage.getTotal() != 0 ? Result.success(bookDtoPage) : Result.error("暂无数据");
    }

    // 测试时间
    @GetMapping("/time")
    public Result timeTest(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime begin,
                           @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime end){
        log.info("时间为：{},{}", begin, end);
        return Result.success("哈哈");
    }






}
